#! /usr/bin/python
# -*- coding: utf-8 -*-

import sys, os.path
from PyQt4 import QtGui, QtCore
import citecheck

class DropArea(QtGui.QTextEdit):
	def __init__(self, parent=None):
		QtGui.QTextEdit.__init__(self, parent)
		self.parent = parent
		
		#~ self.setText(self.trUtf8("<drop here>"))
		self.setMinimumSize(300, 100)
		self.setFrameStyle(QtGui.QFrame.Sunken | QtGui.QFrame.StyledPanel)
		#~ self.setAlignment(QtCore.Qt.AlignCenter)
		self.setAcceptDrops(True)
		self.setAutoFillBackground(True)
		self.setBackgroundRole(QtGui.QPalette.Button)
		self.setReadOnly(True)
	
	def clear(self):
		self.setText(self.trUtf8(""))
		self.setBackgroundRole(QtGui.QPalette.Button)
	
	def dragEnterEvent(self, event):
		#~ self.setText(self.trUtf8("<drop content>"))
		self.setBackgroundRole(QtGui.QPalette.Highlight)
		event.acceptProposedAction()
	
	def dragMoveEvent(self, event):
		event.acceptProposedAction()
	
	def dragLeaveEvent(self, event):
		#~ self.clear()
		event.accept()
	
	def dropEvent(self, event):
		if event.mimeData().hasUrls():
			L = event.mimeData().urls()
			file_list = [unicode(r.toLocalFile()) for r in L]
			self.emit(QtCore.SIGNAL("handle_file_list"), file_list)
		self.setBackgroundRole(QtGui.QPalette.Button)
		event.acceptProposedAction()
	
	def block_drop(self):
		self.setAcceptDrops(False)
		self.setBackgroundRole(QtGui.QPalette.Button)
	
	def allow_drop(self):
		self.setAcceptDrops(True)
		self.setBackgroundRole(QtGui.QPalette.Base)


class MainWindow(QtGui.QWidget):
	def __init__(self, parent=None):
		QtGui.QWidget.__init__(self, parent)
		self.parent = parent
		
		self.setAcceptDrops(True)
		
		self.setWindowTitle("citecheck")
		#~ self.setWindowIcon(QtGui.QIcon("icons/16x16.png"))
		
		#-- Main layout
		self.vL = QtGui.QVBoxLayout()
		self.setLayout(self.vL)
		
		#-- Opened file
		self.filePath = QtGui.QLineEdit(self)
		self.filePath.setReadOnly(True)
		self.filePath.setEnabled(False)
		self.vL.addWidget(self.filePath)
		
		#-- If want to add options, should be added here
		
		#-- The splitter between ref list and text editor
		self.hL = QtGui.QSplitter(QtCore.Qt.Horizontal)
		self.vL.addWidget(self.hL)
		
		#-- The status bar
		self.statusLabel = QtGui.QLabel("...")
		self.statusLabel.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Sunken)
		self.statusLabel.setMaximumHeight(20)
		self.vL.addWidget(self.statusLabel)
		
		#-- Left Frame in the splitter
		f = QtGui.QFrame()
		m = -9
		f.setContentsMargins(m,m,m,m)
		vL = QtGui.QVBoxLayout(f)
		self.hL.addWidget(f)
		
		#-- Drop zone / Text editor
		self.textEditor = DropArea(self)
		vL.addWidget(self.textEditor)
		#~ self.textEditor.setStyleSheet("em {font-style: normal; background-color: #ff0;}")
		
		#-- List of references
		self.refList = QtGui.QTreeWidget(self)
		self.refList.setColumnCount(1)
		self.refList.setHeaderLabels([self.trUtf8("References")])
		self.refList.setFrameStyle(QtGui.QFrame.Sunken | QtGui.QFrame.StyledPanel)
		self.refList.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
		self.refList.setMinimumSize(400,50)
		self.refList.setAlternatingRowColors(True)
		self.hL.addWidget(self.refList)
		
		self.connect(self.textEditor, QtCore.SIGNAL("handle_file_list"), self.handle_file_list)
		self.connect(self.refList, QtCore.SIGNAL("itemClicked(QTreeWidgetItem*,int)"), self.ref_click)
		#~ self.connect(self, QtCore.SIGNAL("messageUpdate(PyQt_PyObject)"), self.updateQueueCell)
		#~ self.connect(self, QtCore.SIGNAL("gotoNextFile"), self.send_next_file)
		#~ self.connect(self.
		
		#~ self.fileList.hide()
	
	def handle_file_list(self, file_list):
		if len( file_list )==0:
			self.statusLabel.setText("The dropped file list is empty...")
			return
		
		QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
		self.textEditor.block_drop()
		self.docFile = file_list[0]
		self.textEditor.clear()
		self.refList.clear()
		self.statusLabel.setText(self.trUtf8("Processing '")+self.docFile+"'...")
		self.process_doc_file()
	
	def process_doc_file(self):
		self.docProcess = DocProcess(self.docFile)
		self.connect(self.docProcess, QtCore.SIGNAL("citecheckDone(PyQt_PyObject)"), self.disp_doc)
		self.docProcess.start()
	
	def disp_doc(self, d):
		
		if not d['ok']:
			self.statusLabel.setText(self.trUtf8("Error: ")+d['refList'])
			self.textEditor.allow_drop()
			QtGui.QApplication.restoreOverrideCursor()
			return
		
		self.statusLabel.setText(self.trUtf8("Done."))
		self.filePath.setText(self.docFile)
		
		self.refData = d
		self.refData['other']['txt'] = self.refData['other']['txt'].replace("\n", "<p/><p>")
		for ref in d['refList']:
			t = QtGui.QTreeWidgetItem(self.refList)
			t.setText(0, ref.decode('utf-8'))
			#~ t.setData(0, QtCore.Qt.UserRole, QtCore.QVariant(d['other']['original_references'][ref]))
		
		self.textEditor.setHtml(self.refData['other']['txt'].decode('utf-8'))
		
		self.textEditor.allow_drop()
		QtGui.QApplication.restoreOverrideCursor()
	
	def ref_click(self, t, col):
		k = unicode(t.text(0))
		ls = self.refData['other']['original_references'][k.encode('utf-8')]
		txt = self.refData['other']['txt']
		c = list()
		for r in ls:
			txt = txt.replace(r, "<span style='background-color: #ff0;'>"+r+"</span>")
			c.append( self.textEditor.document().find(r.decode('utf-8')).position() )
		self.textEditor.setHtml(txt.decode('utf-8'))
		cu = QtGui.QTextCursor(self.textEditor.document())
		cu.setPosition(min(c))
		self.textEditor.setTextCursor(cu)
		self.textEditor.ensureCursorVisible()
		
		

#======================================================================

class DocProcess(QtCore.QThread):
	def __init__(self, docFile):
		QtCore.QThread.__init__(self)
		self.docFile = docFile
	
	def run(self):
		ok, refList, other = citecheck.get_references(self.docFile)
		self.emit(QtCore.SIGNAL("citecheckDone(PyQt_PyObject)"), {'ok': ok, 'refList': refList, 'other': other})


#======================================================================

if __name__=="__main__":
	app = QtGui.QApplication(sys.argv)
	app.setApplicationName("citecheck")
	mainwindow = MainWindow()
	mainwindow.show()
	sys.exit(app.exec_())
